#include <string.h>
#include "dir.h"
#include <vector>
#include <archive.h>

class CArch : public CDir {

  virtual void refresh();

public:

  class CBinFile : public CFile {
  public:
    std::vector< std::pair<void*, size_t> > vdata;

  public:
    CBinFile(const std::string &_name, struct archive *pa) : CFile(_name) {
      read_data(pa);
      std::cerr << "CBinFile::CBinFile : " << vdata.size() << " blocks" << std::endl;
    }

    void read_data(struct archive *pa) {
      int i;
      const void *buff;
      size_t len;
      off_t offset;
      while (ARCHIVE_EOF != (i = archive_read_data_block(pa, &buff, &len, &offset))) {
        void *p = new char[len];
        memcpy(p, buff, len);
        vdata.push_back(std::pair<void*, size_t>(p, len));
      } 
    }
    friend class CArchTextFile;
  };

  class CArchTextFile : public CTextFile {
    CBinFile *pbf;

  public:
    CArchTextFile(const std::string &_name, CBinFile *_pbf) : CTextFile(_name), pbf(_pbf) {
      std::cerr << "CArchTextFile::CArchTextFile ..." << std::endl;
      read();
    }

    virtual void read() {
//      std::cerr << "starting read ..." << std::endl;
      std::string s;
      for (size_t i = 0; i < pbf->vdata.size(); i++) {
        char *pc = (char*)pbf->vdata[i].first;
//        std::string s;
        for (size_t j = 0; j < pbf->vdata[i].second; j++) {
          
          if ('\n' == pc[j]) {
            vl.push_back(s);
            //std::cerr << "S: " << s << std::endl;
            s = "";
          } else {
            s += pc[j];
          }
        }
      }
      if (s.size() > 0) vl.push_back(s);
    }
  };
    

  CArch(const std::string &_name) : CDir(_name) {
    std::cerr << "CArch:" << std::endl; }
};


